package com.why.whypaydemo.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.system.SystemUtil;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.*;

/**
 * 封装http get post
 */
public class HttpUtils {


    private static  final Gson gson = new Gson();

    /**
     * get方法
     * @param url
     * @return
     */
    public static Map<String,Object> doGet(String url){

        Map<String,Object> map = new HashMap<>();
        CloseableHttpClient httpClient =  HttpClients.createDefault();

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        try{
           HttpResponse httpResponse = httpClient.execute(httpGet);
           if(httpResponse.getStatusLine().getStatusCode() == 200){

              String jsonResult = EntityUtils.toString( httpResponse.getEntity());
               map = gson.fromJson(jsonResult,map.getClass());
           }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return map;
    }


    /**
     * 封装post
     * @return
     */
    public static String doPost(String url, String data,int timeout){
        CloseableHttpClient httpClient =  HttpClients.createDefault();
        //超时设置

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(timeout) //连接超时
                .setConnectionRequestTimeout(timeout)//请求超时
                .setSocketTimeout(timeout)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();


        HttpPost httpPost  = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type","text/html; chartset=UTF-8");

        if(data != null && data instanceof  String){ //使用字符串传参
            StringEntity stringEntity = new StringEntity(data,"UTF-8");
            httpPost.setEntity(stringEntity);
        }

        try{

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(httpEntity);
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return null;

    }

    public static void main(String[] args) {
//        // 微信自动转账
//        // 商户账号appid
//        String mchAppid = PayConfigUtil.WEIXIN_APPID_DOCTOR;
//        // 商户号
//        String mchId = PayConfigUtil.WEIXIN_MCH_ID;
//        // 随机字符串
//        String nonceStr = RandomUtil.randomNumbers(16);
//        // 商户订单号
//        String partnerTradeNo = po.getTransactionNum();
//        // 用户openid
//        String openId = "owrrewUzRMu9SFzC5my8veFmtMNA";
//        // 校验用户姓名选项 NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名
//        String checkName = "FORCE_CHECK";
//        // 收款用户姓名
//        String reUserName = doctor.getNickName();
//        // 金额(分)
//        amount = String.valueOf(Integer.parseInt(String.format("%.2f", Float.parseFloat(amount)).replace(".", "")));
//        // Ip地址
//        String serviceIp = SystemUtil.getHostInfo().getAddress();
//
//        String appSecret = PayConfigUtil.WEIXIN_APP_SECRET_DOCTOR;
//        String appKey = PayConfigUtil.WEIXIN_API_KEY;
//
//        // 获取签名
//        SortedMap<String, String> packageParams = new TreeMap<>();
//        packageParams.put("mch_appid", mchAppid);
//        packageParams.put("mchid", mchId);
//        packageParams.put("nonce_str", nonceStr);
//        packageParams.put("partner_trade_no", partnerTradeNo);
//        packageParams.put("openid", openId);
//        packageParams.put("check_name", checkName);
//        packageParams.put("re_user_name", reUserName);
//        packageParams.put("amount", amount);
//        packageParams.put("desc", remark);
//        packageParams.put("spbill_create_ip", serviceIp);
//
//        RequestHandler reqHandler = new RequestHandler(request, response);
//        reqHandler.init(mchAppid, appSecret, appKey);
//
//        // 签名
////            String sign = reqHandler.createSign(packageParams);
//        String sign = WXUtil.createSign(packageParams, PayConfigUtil.WEIXIN_API_KEY);
//        packageParams.put("sign", sign);
//        //            String xmlParam = PaymentKit.toXml(packageParams);
//        String xmlParam = WXUtil.mapToXml(packageParams);
//        LOG.info("微信打款参数：  \n" + xmlParam);
//
//        Map<String, String> resultMap = new HashMap<>();
//
//        try {
//            String postResult = HttpUtils.postSSL(PayConfigUtil.WEXIN_URL_TRANSFERS, xmlParam, config.getWxcert(), PayConfigUtil.WEIXIN_MCH_ID);
//            Document document = DocumentHelper.parseText(postResult);
//            Element rootElt = document.getRootElement();
//            List<Element> list = rootElt.elements();
//            for (Element element : list) {
//                resultMap.put(element.getName(), element.getText());
//            }
//        } catch (Exception e) {
//            LOG.error(e);
//            LOG.error(resultMap.get("return_msg"), e);
//            result.setDefultFailInfo("转账失败,请联系管理员!");
//            return result;
//        }
//
//        if (resultMap.get("return_code").equals("SUCCESS")) {
//            if (!resultMap.get("result_code").equals("SUCCESS")) {
//                LOG.error(resultMap.get("err_code"));
//                result.setDefultFailInfo(resultMap.get("err_code_des"));
//                return result;
//            }
//        }
    }





}
